# -*- coding:utf-8 -*-

import pickle

# 文件序列化和反序列化
"""
filename = 'abc.txt'

d = {'a':1,'b':'abc','c':[1,2,3]}
l = list('123')
i = 99

with open(filename,'wb') as f:
    pickle.dump(d,f)
    pickle.dump(1,f)
    pickle.dump(i,f)

with open(filename,'rb') as f:
    print(f.read(),f.seek(0))
    for _ in range(3):
        x = pickle.load(f)
        print(type(x),x)


# 对象序列化
class AA:
    tt = 'ABC'
    def show(self):
        print('abc')

a1 = AA()

SR = pickle.dumps(a1)
print('sr={}'.format(SR))

a2 = pickle.loads(SR)
print(a2.tt)
a2.show()
# 保存了一个类名,只序列化一个AA类名,反序列化时找到类就可以恢复一个对象.
"""


# 定义类
"""
class AAA:
    def __init__(self):
        self.tt = 'abc'

# 创建类的实例
a1 = AAA()

# 序列化
ser = pickle.dumps(a1)
print('ser={}'.format(ser))

# 反序列化
a2 = pickle.loads(ser)
print(a2,type(a2))
print(a2.tt)
print(id(a1),id(a2))
# 序列化了tt和abc,因为这是每一个对象自己的属性,每一个对象不一样.
"""

import json

d = {'name':'Tom','age':20,'interest':['music','movie']}
j = json.dumps(d)
print(j)



import msgpack
import json

# 源数据
d = {'person':[{'name':'tom','age':18},{'name':'jerry','age':16}],'total':2}

j = json.dumps(d)
m = msgpack.dumps(d)  # 本质就是packb

print("json = {},msgpack={}".format(len(j),len(m)))
print(j.encode(),len(j.encode()))
print(m)

u = msgpack.unpackb(m)
print(type(u),u)

u = msgpack.unpackb(m,encoding='utf8')
print(type(u),u)

